package org.oschina.api.manage.config.service;

import java.util.List;

import org.apache.commons.beanutils.ConvertUtils;
import org.oschina.Message;
import org.oschina.Module;
import org.oschina.ResultUtil;
import org.oschina.api.BaseService;
import org.oschina.api.manage.config.dao.ConfigDAO;
import org.oschina.api.manage.config.model.Config;
import org.oschina.api.manage.config.vo.ConfigVo;
import org.oschina.bean.Result;
import org.oschina.security.annotation.Require;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ConfigService extends BaseService {

	private final static Logger logger=LoggerFactory.getLogger(ConfigService.class);
	
	@Autowired
	private ConfigDAO configDAO;
	
	/**
	 * 返回
	 * @return
	 */
	@Require(authorization=Module.MODULE_6)
	public List<ConfigVo> findVo()
	{
		return configDAO.findVo();
	}
	
	/**
	 * 更新
	 * @param config
	 * @return
	 */
	@Require(authorization=Module.MODULE_6)
	public Result update(Config config)
	{
		if(configDAO.update(config)==0)
			return ResultUtil.getFailure(Message.ERROR_DATA_ERROR);
		
		return ResultUtil.getSuccess(config);
	}
	
	/**
	 * 返回配置
	 * @param <T>
	 * @param id
	 * @param type
	 * @return
	 */
	public <T> Object getValueById(int id,Class<T> type)
	{
		ConfigVo configVo=_findVoById(id);
		if(configVo==null)
		{
			logger.error("ID为 '{}' 的配置为空",id);
			return null;
		}
		
		return ConvertUtils.convert(configVo.getValue(), type);
	}

	private ConfigVo _findVoById(int id)
	{
		return configDAO.findVoById(id);
	}
}